import React, { Component } from 'react';
import { NavigationEvents } from 'react-navigation';
import {
  StyleSheet, Text, View, TouchableOpacity,
  Image, PixelRatio, FlatList, Alert
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import HTTP from '../../../../utils/http';
import ToastUtil from '../../../../utils/toast';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import { Common } from '../../../../component/common/Common';
import { OrderCommon } from '../../../order-new/_common/common';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { NewAccountHome } from '../../../../components/common/newAccountHome';
import { ProgressModal } from '../../../../components/common/ProgressModal';
import OrderDetailsService from '../../../order-new/details/_common/service';

const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../../imgs/sanjiao3.png')

const LIST = [
  {
    label: '企业创建',
    params: {
      applyType: 'ADD',
    }
  },
  {
    label: '企业变更',
    params: {
      applyType: 'CHANGE',
    }
  }
]

export class EnterpriseListsPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '企业待审批',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      tabIndex: 0,
      companyIndex: 0,
      tabItem: 0,
      status: 'data',
      refreshIcon: false,
      listData: [],
      itemData: {},
      params: {
        applyType: 'ADD',
      },
      isTablet: true,
      cntList: true,
      isDataItem: true,
      itemAuditingletedCnt: '0',
      itemAuditRejectCntCnt: '0',
      totalPage: '0',
      alertShow: false,
      options: [],
      choice: {},
      lightBoxData: {
        modalVisible: false,
        onClosePress: this._closeLightBox,
        title: '',
        rowDataList: [],
        status: 'data',
        refreshIcon: false,
      },
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1;
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
    }
  }

  async componentDidMount() {
    await this.init();
    await this.initPage();
  }

  //获取业务组织
  // async  getSorage () {
  //   const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
  //   const userInfo = JSON.parse(userInfoJson);
  //   this.setState({
  //     options: userInfo.corpInfoTOs || [],
  //     choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
  //   })
  // }


  //初始化数据
  init = async () => {
    let options = await HTTP.GET(API_GENERATE(API.AUDIT_CNT_NEW))
    // let resTableList = await HTTP.GET(API_GENERATE(API.AUDIT_CNT), { corpId: this.state.options[this.state.companyIndex].corpId })
    if (options) {
      options.map(item => {
        item.rowCount = item.taskCnt
      })
      this.setState({
        options,
        choice: options[this.state.companyIndex] || {}
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  initPage = async (refreshIcon) => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    this.params = {
      pageNo: this.pageParams.pageNo,
      pageSize: this.pageParams.pageSize,
      applyType: this.state.params.applyType,
      corpId: this.state.options[this.state.companyIndex].corpId
    }
    let res = await HTTP.POST(API_GENERATE(API.AUDIT_LIST), this.params)
    if (res) {
      let responseData = res.rows;
      this.setState({
        listData: this.pageParams.pageNo == '1' ? responseData : this.state.listData.concat(responseData),
        status: responseData.length > 0 ? 'data' : 'empty',
        refreshIcon: false,
        totalPage: res.totalPage,

      })
      this.pageParams.pageNo = res.pageNo++;
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  _getCheckApprove = async (data) => {
    let { listData } = this.state;
    //查询审批节点AUDIT_QUERY_COMPANY
    let params = {
      bizId: data.applyId,
      bizObjType: 'COMPANY_INFO_AUDIT',
      processInstanceId: data.processInstanceId,
      // businessKey:data.businessKey,
      // formKey:data.formKey,
      // taskId:data.taskId
    }
    let responseData1 = await HTTP.GET(API_GENERATE(API.AUDIT_QUERY_COMPANY), params)
    responseData1 = responseData1 && responseData1.map((item) => {
      if (item.auditResult == 9) {
        item.auditResultName = '操作';
      }
      return item;
    })
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = true;
    lightBoxData.title = '审批流';
    lightBoxData.rowDataList = responseData1;
    this.setState({
      lightBoxData,
      status: 'data'
    })
  }

  _closeLightBox = () => {
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = false;
    this.setState({ lightBoxData });
  }

  loadMore = () => {
    if (this.state.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  refresh = () => {
    this.pageParams.pageNo = 1;
    if (this.state.totalPage >= this.pageParams.pageNo) {
      this.reload = false;
      this.initPage();
    }
  }

  _tabList = (items, tabItem) => {
    this.reload = true;
    this.pageParams.pageNo = 1;
    this.setState({
      tabItem,
      params: {
        applyType: items.params.applyType,
      },
      totalPage: '0',
      alertShow: false
    }, () => {
      this.pageParams.pageNo = 1;
      this.initPage();
    })

  }

  onErrorRefresh = () => {
    let { tabIndex } = this.state;
    if (tabIndex != 2) {
      this.initPage();
    }
  }



  goSkipPage = (item) => {
    let { tabItem, choice } = this.state;
    if (tabItem == 0) {
      this.props.navigation.navigate('EnterpriseDetailsPage', {
        tabIndex: 0,
        companyId: item.companyId,
        id: item.applyId,
        title: item.companyName,
        status: 0,
        choice
      })
    } else {
      this.props.navigation.navigate('EnterpriseChangePage', {
        applyId: item.applyId,
        businessKey: item.businessKey,
        formKey: item.formKey,
        taskId: item.taskId,
        leadership: true,
        choice
      })
    }
  }

  // 审批
  approve = async () => {
    const { itemData, choice } = this.state;
    if (this.requesting) return;
    this.setState({ showRejectModal: false });
    this.requesting = true;
    let requestParams = {
      applyId: itemData.applyId,
      companyId: itemData.companyId,
      auditResult: this.auditResult,
      remark: this.remark,
      corpId: choice.corpId,
      businessKey: itemData.businessKey,
      formKey: itemData.formKey,
      taskId: itemData.taskId
    };
    let text = this.auditResult ? '同意' : '驳回';
    this.setState({ status: 'loading' });
    let res = await HTTP.POST(API_GENERATE(API.ENTERPRISE_AUDIT), requestParams);
    this.requesting = false;
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.reloadPage()
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }

  reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.initPage();
  }


  _approvalListItim = (data) => {
    let { tabItem, } = this.state
    let item = data.item;
    return (
      <View style={{
        marginTop: 20 * scale, paddingLeft: 12 * scale,
        paddingRight: 12 * scale,
      }}>
        <View style={{ marginBottom: 7 * scale, flexDirection: 'row', justifyContent: 'flex-end' }}>
          <Text style={styles.itemLightText}>{item.createDate || '--'}</Text>
        </View>
        <TouchableOpacity activeOpacity={.6} style={styles.itemWrap}
          onPress={() => {
            this.goSkipPage(item)
          }}
        >
          <View style={{ flexDirection: 'row', marginBottom: 8 * scale, marginTop: 5 * scale, paddingLeft: 12 * scale, paddingRight: 12 * scale, alignItems: 'center', }}>
            <View style={{ flexDirection: 'row', alignItems: 'flex-start', width: 200 * scale }}>
              <Text style={styles.itemLightText}>{item.companyName || '--'}</Text>

              {tabItem == 0 && item.isForeign == 0 ? (
                <View style={{
                  justifyContent: 'flex-start',
                  marginLeft: 10 * scale,
                }}>
                  <Image style={styles.itemName} source={OrderCommon.iconData.innerImg} />
                </View>
              ) : tabItem == 0 && item.isForeign == 1 ?
                  (<View style={{
                    justifyContent: 'flex-start',
                    marginLeft: 10 * scale,
                  }}>
                    <Image style={styles.itemName} source={OrderCommon.iconData.outerImg} />
                  </View>
                  ) : tabItem == 0 && item.isForeign == 2 ? (
                    <View style={{
                      justifyContent: 'flex-start',
                      marginLeft: 10 * scale,
                      paddingLeft: 20 * scale,
                      paddingRight: 20 * scale,
                      position: 'relative',
                      flexDirection: 'row',
                    }}>
                      <Image style={styles.itemName} source={OrderCommon.iconData.innerImg} />
                      <Image style={[styles.itemName, styles.itemNames]} source={OrderCommon.iconData.outerImg} />
                    </View>
                  ) : null
              }

            </View>


            <View style={{
              marginBottom: 1 * scale, paddingTop: 2 * scale, position: 'absolute',
              top: 0,
              right: 28 * scale,
            }}>
              <Text style={styles.itemLightColor}>{tabItem == 0 ? '企业创建' : tabItem == 1 && item.applyType == 'CONVERT' ? '转外贸' : '企业变更'}</Text>
            </View>
          </View>
          <Text style={{ fontSize: 10 * scale, paddingBottom: 12 * scale, paddingLeft: 12 * scale, color: '#848A96' }}>(业务组织：{this.state.options[this.state.companyIndex].corpName || '-'})</Text>
          <View style={styles.itemBorder}></View>
          <View style={{ marginBottom: 15 * scale, marginTop: 10 * scale, }}>
            {/* {'评级' && <View style={{ flexDirection: 'row', alignItems: 'center', position: 'relative', paddingRight: 20 * scale, paddingLeft: 12 * scale, paddingRight: 12 * scale, marginBottom: 10 * scale }}>
              <View style={styles.itemType}>
                <Text style={{ color: '#000000', fontSize: 12 * scale, fontWeight: '300' }}>企业升级</Text>
              </View>
              <Text style={{ color: '#000000', fontSize: 12 * scale, fontWeight: '600' }}>{'升2级'}</Text>
              <Text style={{ color: style.color.themeColor, fontSize: 12 * scale, fontWeight: '600' }} onPress={() => Alert.alert('申请备注')}>【{'申请备注'}】</Text>
            </View>} */}
            <View style={{ flexDirection: 'row', position: 'relative', marginBottom: 15 * scale, paddingLeft: 12 * scale, paddingRight: 12 * scale, }}>
              <View style={styles.itemType}>
                <Text style={{ color: '#000000', fontSize: 12 * scale, fontWeight: '300', marginTop: 1 * scale }}>操作人</Text>
              </View>
              <Text style={{ color: '#000000', fontSize: 12 * scale, fontWeight: '600', flexDirection: 'row', width: 210 * scale }}>
                {item.staffName || '--'} | {item.bizTeamName || '--'}
              </Text>
              {/* <Text style={{ color: '#000000', fontSize: 12 * scale, fontWeight: '600', marginLeft: 10 * scale }}></Text> */}
              <Image source={arrowIcon} style={styles.arrowIcon} />
            </View>
            <View style={styles.itemBorder}></View>
            <View style={styles.itemBottom}>
              <TouchableOpacity onPress={() => { this._getCheckApprove(item) }}>
                <Text style={styles.itemBottomText}>审批流</Text>
              </TouchableOpacity>
              <View style={styles.itemDayTime}>
                <Text style={[styles.consent, styles.consentColor]} onPress={() => {
                  this.auditResult = 1;
                  this.remark = '';
                  this.setState({
                    showRejectModal: true,
                    itemData: item,
                  })
                  // this.consentCreate(item)
                }}>同意</Text>
                <Text style={styles.itemdown} onPress={() => {
                  if (item) {
                    this.auditResult = 0;
                    this.remark = '';
                    this.setState({
                      showRejectModal: true,
                      itemData: item,
                    })
                  } else {
                    ToastUtil.showWarning('没有数据')
                  }
                }}>驳回</Text>
              </View>
            </View>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  render() {
    let { tabIndex, listData, tabItem, refreshIcon, status, resAuditcntList, showRejectModal, alertShow, choice, options, lightBoxData } = this.state;
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={async () => {
          await this.init();
          await this.initPage();
        }} />
        {options.length > 1 ?
          <NewAccountHome
            fn={(val) => {
              this.setState({ companyIndex: val }, () => {
                this.pageParams.pageNo = 1;
                this.init();
                this.initPage();
              })
            }}
            options={options}
            choice={choice} />
          : null}
        <View style={[styles.stateView, styles.marginStyle]}>
          {LIST.map((items, index) => {
            return (
              <TouchableOpacity key={index} style={[styles.stateItem, tabItem == index ? styles.stateItemActive : null]} onPress={() => { this._tabList(items, index) }}>
                <Text style={[styles.stateItemText, tabItem == index ? styles.stateItemTextActive : null]}>{items.label}</Text>
                {choice ?
                  <View style={(index == 0 && choice.custAddCnt > 0) || (index == 1 && choice.custChangeCnt > 0) ? styles.stateItemInfo : null}></View>
                  : null
                }
              </TouchableOpacity>
            )
          })
          }
        </View>
        {
          status == 'data' ? (
            (
              <View style={styles.body}>
                <FlatList
                  data={listData}
                  renderItem={
                    this._approvalListItim
                  }
                  refreshing={refreshIcon}
                  onRefresh={() => { this.refresh() }}
                  onEndReachedThreshold={1}
                  onEndReached={() => { this.loadMore() }}
                />
              </View>
            )
          ) : (<View style={{ flex: 1 }}>
            <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
          </View>)
        }
        <RefuseModal
          titleText={'审批意见'}
          placeholderText={this.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.remark = text;
            this.approve();
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
        <ProgressModal {...lightBoxData} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray
  },
  headBox: {
    backgroundColor: style.color.themeColor,
    height: 50 * scale,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around'
  },
  tabItems: {
    color: style.color.white,
    fontSize: 12 * scale,
    width: '35%',
    textAlign: 'center',
    marginTop: 20 * scale,
    opacity: .8
  },
  marginStyle: {
    marginLeft: 15 * scale,
    marginRight: 15 * scale
  },
  tabItemActive: {
    opacity: 1
  },
  stateView: {
    flexDirection: 'row',
    marginTop: 15 * scale,
    marginBottom: 15 * scale
  },
  stateItem: {
    // paddingTop: 10 * scale,
    // paddingBottom: 10 * scale,
    // paddingLeft: 10 * scale,
    // paddingRight: 10 * scale,
    padding: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 20 * scale,
    marginRight: 10 * scale,
    flexDirection: 'row'
  },
  stateItemText: {
    paddingLeft: 2 * scale,
    paddingRight: 2 * scale,
    fontSize: 11 * scale,
    color: style.color.themeColor,
    fontWeight: '500',
  },
  stateItemInfo: {
    width: 5 * scale,
    height: 5 * scale,
    backgroundColor: style.color.fontRed1,
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  stateItemActive: {
    backgroundColor: style.color.themeColor,
  },
  stateActive: {
    backgroundColor: style.color.white,
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemInfoActive: {
    backgroundColor: style.color.white
  },
  body: {
    flex: 1,
    backgroundColor: style.color.bgGray
  },
  itemLightText: {
    fontSize: 12 * scale,
    color: '#272727',
    fontWeight: '500',
    flexWrap: 'wrap'
  },
  itemName: {

  },
  itemNames: {
    marginLeft: 5 * scale
  },
  itemAccount: {
    fontSize: 12 * scale,
    color: '#272727',
  },
  itemDayTime: {
    justifyContent: 'flex-end',
    flex: 1,
    flexDirection: 'row'
  },
  itemBottom: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: "center",
  },
  itemBottomText: {
    color: '#0091FF',
    fontSize: 12 * scale,
    padding: 20 * scale,
    paddingVertical: 10 * scale,
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    // marginRight: 0 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  consentColor: {
    // backgroundColor: style.color.themeColor,
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
  itemTime: {
    fontSize: 12 * scale,
    color: '#272727',
    opacity: .8,
    paddingTop: 10 * scale,
    paddingRight: 10 * scale,
    // paddingRight:12 *scale,
    // justifyContent:'flex-end',
    // flex:1,
    // flexDirection:'row'
  },
  itemWrap: {
    backgroundColor: '#fff',
    width: '100%',
    borderRadius: 8 * scale,
    // paddingLeft: 12 * scale,
    // paddingRight: 12 * scale,
    // paddingBottom: 14 * scale,
    paddingTop: 14 * scale,
  },
  itemType: {
    // height: 20 * scale,
    width: 58 * scale,
    flexDirection: 'row',
    alignItems: 'flex-start',
    // justifyContent: 'center',
    // flex: 4,
    // backgroundColor: '#FA9B22',
    borderRadius: 4 * scale,
    marginRight: 10 * scale,
  },
  itemLightColor: {
    // justifyContent: 'flex-end',
    fontSize: 12 * scale,

    // marginRight: 16 * scale,
    color: '#F60202',
    fontWeight: '500',
  },
  itemBorder: {
    height: 1 * scale,
    backgroundColor: '#E3E7F0',
    marginBottom: 15 * scale,
  },
  arrowIcon: {
    width: 8 * scale,
    height: 12 * scale,
    position: 'absolute',
    right: 0,
    top: 2 * scale,
    right: 32 * scale,
  },
  itemApplyAmount: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    paddingRight: 10 * scale,
  },
  accountSelect: {
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  }

})